package com.lucene.blog.controller;

import java.sql.SQLException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.lucene.blog.bean.Blogger;
import com.lucene.blog.db.service.BloggerService;
import com.lucene.blog.util.CryptographyUtil;

/**
 * 博主Controller层，前台部分不需要验证
 * @author yachao
 *
 */
@Controller
@RequestMapping("/blogger")
public class BloggerController {
	
	@Resource
	private BloggerService bloggerService;
	
	@RequestMapping("/login")
	public String login(Blogger blogger, HttpServletRequest request) {
		Subject subject = SecurityUtils.getSubject();
		String newPassword = CryptographyUtil.md5(blogger.getPassword(), "javacoder");
		
		UsernamePasswordToken token = new UsernamePasswordToken(blogger.getNickname(), newPassword);
		
		try {
			subject.login(token);
			return "redirect:/admin/main.jsp";
		} catch(AuthenticationException ex) {
			ex.printStackTrace();
			request.setAttribute("blogger", blogger);
			request.setAttribute("errorInfo", "用户名或密码错误!");
			return "login";
		}
	}
	
	@RequestMapping("/aboutBlogger")
	public ModelAndView aboutBlogger() {
		ModelAndView modelAndView = new ModelAndView();
		Blogger blogger = null;
		try {
			blogger = bloggerService.getBloggerData();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		modelAndView.addObject("blogger", blogger);
		modelAndView.addObject("commonPage", "front/blogger/bloggerInfo.jsp");
		modelAndView.addObject("title", "关于博主");
		modelAndView.setViewName("mainTemp");
		return modelAndView;
	}
	
	@RequestMapping("/myAlbum")
	public ModelAndView myAlbum() {
		ModelAndView modelAndView = new ModelAndView();
		// 要写一个相册的service获取相册
		// 需要创建一个相册表
		modelAndView.addObject("commonPage", "front/blogger/myAlbum.jsp");
		modelAndView.setViewName("mainTemp");
		return modelAndView;
	}
	
	@RequestMapping("/resource")
	public ModelAndView resource() {
		ModelAndView modelAndView = new ModelAndView();
		// 要写一个资源的service获取资源
		// 需要创建一个资源表
		modelAndView.addObject("commonPage", "front/blogger/resource.jsp");
		modelAndView.setViewName("mainTemp");
		return modelAndView;
	}
}
